/*********************************************************************************
 *      Copyright:  (C) 2022 South-Central Minzu University
 *                  All rights reserved.
 *
 *       Filename:  sqliteall.c
 *    Description:  This file :API function of server database
 *                 
 *        Version:  1.0.0(20/04/22)
 *         Author:  zhangkang <2980640573@qq.com>
 *      ChangeLog:  1, Release initial version on "20/04/22 01:43:55"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#include "sqlite3.h"
#include "logger.h"

#define  table_name "ser_temp"

static sqlite3    *db=NULL;

int callback(void *NotUsed, int argc, char **argv, char **azColName) 
{
   int i;
   for(i=0; i<argc; i++)
   {
      log_info("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
   }
   return 0;
}

int sqlite_init(char * db_name)      
{
    char                     buf_table[128];
    char                    *zErrMsg = NULL;
    
    
    if( !db_name )
    {
        log_error("ERROR: Invalid input arguments\n");
        return -1;
    }
    
                 /* Open database */
    if( SQLITE_OK != sqlite3_open(db_name,&db) )
    {
        log_error("Error open database: %s\n", zErrMsg);
        sqlite3_free(zErrMsg);
        return -2;
    }
    
                        /*Creat table*/    
    memset(buf_table,0,sizeof(buf_table));
    snprintf(buf_table, sizeof(buf_table),"CREATE TABLE %s(ID INTEGER PRIMARY KEY AUTOINCREMENT, SN CHAR(20),DATIME CHAR(100),TEMPERATURE CHAR(50));", table_name);
	  if( SQLITE_OK != sqlite3_exec(db, buf_table, callback, 0, &zErrMsg))
	  {
        log_warn("create table error:%s\n", zErrMsg);
		    sqlite3_free(zErrMsg);
        return -3;
	  }
    else
    {
        log_info("create table scuessfully\n");
        return 0;
    }
    
}

int sqlite_insert_data(char *buf_data[])     
{
    char 	 *zErrMsg = NULL;
    char    buf_insert[256]; 
    
    
    memset(buf_insert,0,sizeof(buf_insert));
    snprintf( buf_insert,sizeof(buf_insert),"INSERT INTO %s VALUES (NULL, '%s', '%s', '%s');",table_name,buf_data[0],buf_data[1],buf_data[2] );
   	
    if(  SQLITE_OK !=sqlite3_exec(db, buf_insert, callback, 0, &zErrMsg) )
	  {
      	printf("sqlite inset table error: %s\n", zErrMsg);
      	sqlite3_free(zErrMsg);
        return -1;
   	}
    log_info("insert data successful\n");
	  return 0;
}


int sqlite_close_db(void)                 
{
    char 	*zErrMsg = NULL;
    
    if( SQLITE_OK != sqlite3_close(db) )
    {
        log_error("Error close database: %s\n", zErrMsg );
        sqlite3_free(zErrMsg);
    }   
    log_info("successfully close database\n");
    return 0;
}